
#include <ros/ros.h>
#include "loop_addition_action/AddIntsAction.h"
#include <actionlib/server/simple_action_server.h>

typedef actionlib::SimpleActionServer<loop_addition_action::AddIntsAction> Server;

//收到Action的goal后调用该回调函数
void goalexecute(const loop_addition_action::AddIntsGoalConstPtr &goal, Server *server)
{
    //获取目标值
    int num = goal->num;
    ROS_INFO("目标值:%d", num);
    //累加并响应连续反馈
    int result = 0;
    loop_addition_action::AddIntsFeedback feedback; //连续反馈
    ros::Rate rate(10);                 //通过频率设置休眠时间
    for (int i = 1; i <= num; i++)
    {
        result += i;
        //组织连续数据并发布
        feedback.progress_bar = i / (double)num;
        server->publishFeedback(feedback);
        rate.sleep();
    }
    //设置最终结果
    loop_addition_action::AddIntsResult r;
    r.result = result;
    server->setSucceeded(r);
    ROS_INFO("最终结果:%d", r.result);
}

int main(int argc, char *argv[])
{
    setlocale(LC_ALL, "");
    ROS_INFO("Action服务端实现");
    // 初始化ROS节点;
    ros::init(argc, argv, "AddInts_server");
    // 创建NodeHandle;
    ros::NodeHandle nh;
    // 创建Action服务对象;
    /*SimpleActionServer(ros::NodeHandle n,
                        std::string name,
                        boost::function<void (const loop_addition_action::AddIntsGoalConstPtr &)> execute_callback,
                        bool auto_start)
    */
    // Actionlib::SimpleActionServer<demo01_Action::AddIntsAction> server(....);
    Server server(nh, "/addInts", boost::bind(&goalexecute, _1, &server), false);
    server.start();
    // 处理请求,产生反馈与响应;
    ros::spin();
    return 0;
}
